package com.chkj.fbook.business.service.impl;

import com.chkj.fbook.business.service.RoomService;
import com.chkj.fbook.business.service.SeatService;
import com.chkj.fbook.common.utils.IDUtils;
import com.chkj.fbook.common.utils.RedisUtil;
import com.chkj.fbook.business.dao.RoomDao;
import com.chkj.fbook.business.domain.RoomDO;
import com.chkj.fbook.business.domain.SeatDO;
import com.chkj.fbook.common.constants.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class RoomServiceImpl implements RoomService {

	@Resource
	private RoomDao roomDao;
	
	@Autowired
	private SeatService seatService;

	@Autowired
	private RedisUtil redisUtil;
	
	@Override
	public RoomDO get(String id){
		return roomDao.get(id);
	}
	
	@Override
	public List<RoomDO> list(Map<String, Object> map){
		return roomDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return roomDao.count(map);
	}
	
	@Override
	@Transactional
	public int save(RoomDO room){
		
		//已存在的排序自增
		roomDao.editAdd1(room);
		
		room.setId(IDUtils.genUUID());
		Date date = new Date();
		room.setCreateTime(date);
		room.setUpdateTime(date);
		roomDao.save(room);
		
		return 1;
	}
	
	@Override
	@Transactional
	public int update(RoomDO room){
		
		//获取旧房间
		RoomDO oldRoomDO = this.get(room.getId());
		
		//先排序自减
		roomDao.editSub1(oldRoomDO);
		
		//再排序自增
		roomDao.editAdd1(room);
		
		room.setUpdateTime(new Date());
		int update1 = roomDao.update(room);
		int update2 = 0;
		
		if(oldRoomDO!=null) {
			//如果门店/房间（名称）有修改，那么维护桌位/座位表的门店/房间（名称）
			if(!room.getName().equals(oldRoomDO.getName())) {
				SeatDO so = new SeatDO();
				so.setRoomId(room.getId());
				so.setRoomName(room.getName());
				update2 = seatService.updateRoomNameByRoomId(so);
			}
		}
		return update1+update2;
	}
	
	@Override
	@Transactional
	public int remove(String id){
		
		//获取删除的房间
		RoomDO oldRoomDO = this.get(id);
		
		//已存在的排序自减
		roomDao.editSub1(oldRoomDO);
		
		return roomDao.remove(id);
	}
	
	@Override
	@Transactional
	public int batchRemove(String[] ids){
		//roomDao.batchRemove(ids);
		for(String id : ids) {
			this.remove(id);
		}
		return 1;
	}

    @Override
    public List<RoomDO> getAll() {
        return roomDao.getAll();
    }

    @Override
    public List<RoomDO> getByOrderDate(String orderDate) {
		String key = Constants.ORDER_ROOM_KEY + orderDate;
		Object o = null;
		try {
			o = redisUtil.get(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (o != null) {
			return (List<RoomDO>) o;
		}
		return roomDao.getByOrderDate(orderDate);
    }

}
